// Dialog hooks方法
export function useDialog(options = {}) {
  // 默认配置
  const defaultOptions = {
    mask: true,
    maskClickClose: false,
    styles: {},
    content: '',
    event: function () {},
    buttons: [{ name: '取消', event: 'cancel' }]
  }

  // 合并配置
  const config = Object.assign({}, defaultOptions, options)

  // 创建弹窗元素相关变量
  let root = null
  let mask = null
  let closeCallback = null

  // 默认样式
  const defaultStyle = {
    position: 'fixed',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%,-50%)',
    background: '#fff',
    zIndex: '10001',
    width: '450rem',
    borderRadius: '10rem',
    fontSize: '18rem',
    boxShadow: '0 8rem 32rem rgba(0,0,0,0.2)',
    overflow: 'hidden'
  }

  const defaultMaskStyle = {
    position: 'fixed',
    top: '0',
    left: '0',
    right: '0',
    bottom: '0',
    background: 'rgba(0, 0, 0, 0.3)',
    zIndex: '10000'
  }

  // 创建弹窗
  function createDialog(dialogOptions = {}) {
    const dialogConfig = Object.assign({}, config, dialogOptions)

    // 清理已存在的弹窗
    close()

    // 创建根元素
    root = document.createElement('div')
    root.setAttribute('data-dialog', 'container')

    // 创建 mask
    if (dialogConfig.mask) {
      mask = document.createElement('div')
      applyStyles(mask, defaultMaskStyle)
      document.body.appendChild(mask)
    }

    // 创建弹窗容器
    applyStyles(root, defaultStyle)

    // header
    if (dialogConfig.styles.header) {
      const header = document.createElement('div')
      applyStyles(
        header,
        mergeStyles(
          {
            padding: '10rem 15rem',
            borderBottom: '1px solid #eee',
            fontWeight: 'bold',
            fontSize: '14rem',
            color: '#333'
          },
          dialogConfig.styles.header || {}
        )
      )
      header.innerHTML = '提示'
      root.appendChild(header)
    }

    // body
    const body = document.createElement('div')
    applyStyles(
      body,
      mergeStyles(
        {
          padding: '25rem',
          color: '#333',
          lineHeight: '1.5'
        },
        dialogConfig.styles.body || {}
      )
    )

    if (typeof dialogConfig.content === 'string') {
      body.innerHTML = dialogConfig.content
    } else if (dialogConfig.content instanceof HTMLElement) {
      body.appendChild(dialogConfig.content)
    }
    root.appendChild(body)

    // footer
    if (dialogConfig.styles.footer) {
      const footer = document.createElement('div')
      applyStyles(
        footer,
        mergeStyles(
          {
            padding: '10rem 15rem',
            textAlign: 'right',
            borderTop: '1px solid #eee'
          },
          dialogConfig.styles.footer || {}
        )
      )

      const btnList =
        dialogConfig.buttons && dialogConfig.buttons.length ? dialogConfig.buttons : [{ name: '取消', event: 'cancel' }]
      for (let i = 0; i < btnList.length; i++) {
        const btnCfg = btnList[i]
        const btn = document.createElement('button')
        btn.innerHTML = btnCfg.name
        btn.setAttribute('data-event', btnCfg.event)
        applyStyles(btn, {
          marginLeft: '10rem',
          padding: '2.5rem 10rem',
          border: '1px solid ' + (btnCfg.color || '#DCDFE6'),
          borderRadius: '10rem',
          background: 'transparent',
          color: btnCfg.color || '#606266',
          cursor: 'pointer',
          fontSize: '14rem',
          lineHeight: '10rem',
          transition: 'all 0.3s'
        })

        footer.appendChild(btn)
      }

      root.appendChild(footer)
    }

    // 添加到页面
    document.body.appendChild(root)

    // 事件委托
    onEvent(root, 'click', function (e) {
      const target = e.target || e.srcElement
      const evtName = target.getAttribute('data-event')

      if (evtName) {
        dialogConfig.event(evtName, e)
      }
    })

    if (mask && dialogConfig.maskClickClose) {
      onEvent(mask, 'click', function (e) {
        dialogConfig.event('mask', e)
        close()
      })
    }

    // 设置关闭回调
    closeCallback = dialogConfig.closeCallback || null

    return {
      root,
      mask
    }
  }

  // 关闭弹窗
  function close() {
    if (mask && mask.parentNode) {
      mask.parentNode.removeChild(mask)
    }
    if (root && root.parentNode) {
      root.parentNode.removeChild(root)
    }
    mask = null
    root = null

    // 执行关闭回调
    if (closeCallback && typeof closeCallback === 'function') {
      closeCallback()
    }
  }

  // 事件处理
  function onEvent(target, type, cb) {
    if (document.addEventListener) {
      target.addEventListener(type, cb)
    } else {
      target.attachEvent('on' + type, cb)
    }
  }

  // 应用样式
  function applyStyles(el, styles) {
    for (const key in styles) {
      if (styles.hasOwnProperty(key)) {
        el.style[key] = styles[key]
      }
    }
  }

  // 合并样式
  function mergeStyles(defaults, custom) {
    const result = {}
    for (const k in defaults) {
      if (defaults.hasOwnProperty(k)) {
        result[k] = defaults[k]
      }
    }
    for (const k in custom) {
      if (custom.hasOwnProperty(k)) {
        result[k] = custom[k]
      }
    }
    return result
  }

  return {
    create: createDialog,
    close
  }
}

/**
 * 移动端抽屉hooks方法
 * @param {Object} options - 配置选项
 * @param {string} options.selector - 抽屉元素选择器
 * @param {string} options.direction - 抽屉方向 (left|right|top|bottom)
 * @param {number} options.duration - 动画持续时间(毫秒)
 * @returns {Object} 包含open和close方法的对象
 */
export function useDrawer(options = {}) {
  // 默认配置
  const defaultOptions = {
    selector: '.drawer',
    direction: 'left',
    duration: 200,
    maskClosable: true,
    width: '50%' // 添加默认宽度配置
  }

  // 合并配置
  const config = Object.assign({}, defaultOptions, options)

  // 获取抽屉元素
  const drawer = document.querySelector(config.selector)
  if (!drawer) {
    console.error(`找不到抽屉元素: ${config.selector}`)
    return
  }

  // 创建遮罩层
  let mask = document.querySelector('.drawer-mask')
  if (!mask) {
    mask = document.createElement('div')
    mask.className = 'drawer-mask'
    mask.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      z-index: 999;
      display: none;
      transition: opacity ${config.duration}ms;
    `
    document.body.appendChild(mask)
  }

  // 初始化抽屉样式
  function initDrawerStyle() {
    const drawerStyle = {
      position: 'fixed',
      zIndex: 1000,
      background: '#fff',
      transition: `transform ${config.duration}ms`,
      boxShadow: '0 0 10px rgba(0, 0, 0, 0.3)'
    }

    switch (config.direction) {
      case 'left':
        drawerStyle.top = '0'
        drawerStyle.left = '0'
        drawerStyle.height = '100%'
        drawerStyle.width = config.width // 应用宽度配置
        drawerStyle.transform = 'translateX(-100%)'
        break
      case 'right':
        drawerStyle.top = '0'
        drawerStyle.right = '0'
        drawerStyle.height = '100%'
        drawerStyle.width = config.width // 应用宽度配置
        drawerStyle.transform = 'translateX(100%)'
        break
      case 'top':
        drawerStyle.top = '0'
        drawerStyle.left = '0'
        drawerStyle.width = '100%'
        drawerStyle.height = config.width // 对于顶部抽屉，高度使用配置的宽度值
        drawerStyle.transform = 'translateY(-100%)'
        break
      case 'bottom':
        drawerStyle.bottom = '0'
        drawerStyle.left = '0'
        drawerStyle.width = '100%'
        drawerStyle.height = config.width // 对于底部抽屉，高度使用配置的宽度值
        drawerStyle.transform = 'translateY(100%)'
        break
    }

    Object.assign(drawer.style, drawerStyle)
  }

  // 打开抽屉
  function open() {
    initDrawerStyle()

    // 显示遮罩
    mask.style.display = 'block'
    setTimeout(() => {
      mask.style.opacity = '1'
    }, 10)

    // 显示抽屉
    drawer.style.transform = 'translate(0, 0)'

    // 防止背景滚动
    document.body.style.overflow = 'hidden'
  }

  // 关闭抽屉
  function close() {
    // 隐藏遮罩
    mask.style.opacity = '0'
    setTimeout(() => {
      mask.style.display = 'none'
    }, config.duration)

    // 隐藏抽屉
    switch (config.direction) {
      case 'left':
        drawer.style.transform = 'translateX(-100%)'
        break
      case 'right':
        drawer.style.transform = 'translateX(100%)'
        break
      case 'top':
        drawer.style.transform = 'translateY(-100%)'
        break
      case 'bottom':
        drawer.style.transform = 'translateY(100%)'
        break
    }

    // 恢复背景滚动
    document.body.style.overflow = ''
  }

  // 点击遮罩关闭
  if (config.maskClosable) {
    mask.addEventListener('click', close)
  }

  // ESC键关闭
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      close()
    }
  })

  return {
    open,
    close
  }
}

/**
 * Toast hooks方法
 * @param {Object} options - 配置选项
 * @returns {Object} 包含show和hide方法的对象
 */
export function useToast(options = {}) {
  // 默认配置
  const defaultOptions = {
    time: 2000,
    containerId: 'toast'
  }

  // 合并配置
  const config = Object.assign({}, defaultOptions, options)

  // 获取或创建toast元素
  let toastEl = document.getElementById(config.containerId)
  if (!toastEl) {
    toastEl = document.createElement('div')
    toastEl.id = config.containerId
    toastEl.className = 'toast'
    toastEl.style.cssText = `
      padding: 10rem 20rem;
      max-width: 80%;
      min-width: 100rem;
      position: fixed;
      bottom: 20%;
      left: 50%;
      z-index: 9999;
      transition: all .2s;
      transform: translate(-50%, -50%);
      border-radius: 12rem;
      background: rgba(0, 0, 0, .35);
      color: #fff;
      white-space: pre-wrap;
      word-break: break-all;
      text-align: center;
      font-size: 26rem;
      line-height: 36rem;
      display: none;
    `
    document.body.appendChild(toastEl)
  }

  let timer = null

  // 显示toast
  function show(text, showOptions = {}) {
    const showConfig = Object.assign({}, config, showOptions)

    toastEl.innerText = text
    toastEl.style.display = 'block'

    clearTimeout(timer)
    timer = setTimeout(() => hide(), showConfig.time)
  }

  // 隐藏toast
  function hide() {
    toastEl.style.display = 'none'
    clearTimeout(timer)
  }

  return {
    show,
    hide
  }
}

/**
 * Tip提示hooks方法
 * @param {Object} options - 配置选项
 * @returns {Object} 包含show和hide方法的对象
 */
export function useTip(options = {}) {
  // 默认配置
  const defaultOptions = {
    time: 5000,
    containerId: 'tips'
  }

  // 合并配置
  const config = Object.assign({}, defaultOptions, options)

  // 获取或创建tip元素
  let tipEl = document.getElementById(config.containerId)
  if (!tipEl) {
    tipEl = document.createElement('div')
    tipEl.id = config.containerId
    tipEl.className = 'tips'
    tipEl.style.cssText = `
      word-spacing: 1px;
      font-size: 28rem;
      color: #ccc;
      animation: animate 2s linear infinite;
      display: none;
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 9999;
      text-align: center;
      width: 100%;
    `
    document.body.appendChild(tipEl)
  }

  let timer = null

  // 显示tip
  function show(text, showOptions = {}) {
    const showConfig = Object.assign({}, config, showOptions)

    tipEl.innerText = text
    tipEl.style.display = 'block'

    clearTimeout(timer)
    timer = setTimeout(() => hide(), showConfig.time)
  }

  // 隐藏tip
  function hide() {
    tipEl.style.display = 'none'
    clearTimeout(timer)
  }

  return {
    show,
    hide
  }
}
